from django import forms
from app.forms.account import BootstrapForm
from app import models
from django.core.exceptions import ValidationError
from app.forms.widgets import ColorRadioSelect

class ProjectModelForm(BootstrapForm,forms.ModelForm):
    bootstrap_class_exclude = ['color']

    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request

    class Meta:
        model = models.Project
        fields = ['name','color','desc']
        widgets = {
            'desc':forms.Textarea,
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }

    def clean_name(self):
        name = self.cleaned_data['name']
        exist = models.Project.objects.filter(name=name,creator=self.request.tracer.user).exists()
        if exist:
            raise ValidationError('您创建的项目已经存在')
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        policy_num = self.request.tracer.price_policy.project_num
        if count >= policy_num:
            raise ValidationError('您的项目额度已用完，请购买套餐')
        return name